package main

import (
	"context"
	"errors"
	"go-gin-init/app/DB/mysql"
	"go-gin-init/app/core"
	"go-gin-init/app/job"
	"go-gin-init/app/job/cyccleJob"
	"go-gin-init/app/logger"
	"go-gin-init/app/routers"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// swagger 中添加header.Authorization:token 校验 token
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
func main() {

	// 初始化配置文件
	core.InitConfig()
	// 初始化日志
	logger.InitZap()
	//logger.InitLogrus()
	// 初始化 orm
	mysql.InitGorm()
	// 初始化 redis
	//cache.RedisInit()
	// 初始化 es
	//elasticsearch.InitEs()

	// 定时任务
	go cyccleJob.Sql2Db()

	router := routers.NewRouter()

	// 优雅启停服务
	server := http.Server{
		Addr:    core.Conf.Server.Port,
		Handler: router,
	}
	zap.L().Info("服务启动，监听端口:" + core.Conf.Server.Port)

	go func() {
		if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			zap.L().Error("server listen err...", zap.Any("error", err))
			return
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	// 阻塞
	<-quit

	ctx, channel := context.WithTimeout(context.Background(), 5*time.Second)
	defer channel()

	if err := server.Shutdown(ctx); err != nil {
		zap.L().Error("server shutdown error...", zap.Any("error", err))
		return
	}
	// 关停job服务
	job.JobServer.Stop()
	zap.L().Info("server exiting..." + core.Conf.Server.Port)

}
